package com.yoo.chat.kit.conversationlist;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gyf.immersionbar.ImmersionBar;

import io.rong.common.RLog;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.yoo.chat.kit.IMCenter;
import com.yoo.chat.kit.config.ConversationListBehaviorListener;
import com.yoo.chat.kit.config.RongConfigCenter;
import com.yoo.chat.kit.conversationlist.model.BaseUiConversation;
import com.yoo.chat.kit.conversationlist.model.GatheredConversation;
import com.yoo.chat.kit.conversationlist.viewmodel.ConversationListViewModel;
import com.yoo.chat.kit.event.EnumEventTag;
import com.yoo.chat.kit.event.Event;
import com.yoo.chat.kit.event.CustomEventTag;
import com.yoo.chat.kit.model.NoticeContent;
import com.yoo.chat.kit.utils.CustomEventUtils;
import com.yoo.chat.kit.utils.PermissionCheckUtil;
import com.yoo.chat.kit.utils.RouteUtils;
import com.yoo.chat.kit.utils.StatusBarUtil;
import com.yoo.chat.kit.widget.FixedLinearLayoutManager;
import com.yoo.chat.kit.widget.adapter.BaseAdapter;
import com.yoo.chat.kit.widget.adapter.ViewHolder;
import com.yoo.chat.kit.widget.refresh.SmartRefreshLayout;
import com.yoo.chat.kit.widget.refresh.api.RefreshLayout;
import com.yoo.chat.kit.widget.refresh.constant.RefreshState;
import com.yoo.chat.kit.widget.refresh.listener.OnLoadMoreListener;
import com.yoo.chat.kit.widget.refresh.listener.OnRefreshListener;
import com.yoo.chat.kit.widget.refresh.wrapper.RongRefreshHeader;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yoo.ons.R;

import io.rong.imlib.RongIMClient;

import java.util.List;

public class ConversationListFragment extends Fragment implements BaseAdapter.OnItemClickListener {
    /*
     * 连接通知状态延迟显示时间。
     * 为了防止连接闪断，不会在断开连接时立即显示连接通知状态，而是在延迟一定时间后显示。
     */
    protected final long NOTICE_SHOW_DELAY_MILLIS = 4000L;
    private final String TAG = ConversationListFragment.class.getSimpleName();
    protected ConversationListAdapter mAdapter;
    protected SwipeRecyclerView mList;
    protected View mNoticeContainerView;
    protected TextView mNoticeContentTv;
    protected ImageView mNoticeIconIv;
    protected ConversationListViewModel mConversationListViewModel;
    protected SmartRefreshLayout mRefreshLayout;
    protected Handler mHandler = new Handler(Looper.getMainLooper());
    protected int mNewState = RecyclerView.SCROLL_STATE_IDLE;
    protected boolean delayRefresh = false;
    private int Permission_Request = 10001;

    {
        mAdapter = onResolveAdapter();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.rc_conversationlist_fragment, null, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!IMCenter.getInstance().isInitialized()) {
            RLog.e(TAG, "Please init SDK first!");
            return;
        }
//        RongIM.getInstance().refreshUserInfoCache(new UserInfo(BaseConfig.Companion.getGetInstance().getString(SpArgument.INSTANCE.getUserCode(),""), BaseConfig.Companion.getGetInstance().getString(SpArgument.INSTANCE.getNickName(), ""), Uri.parse(BaseConfig.Companion.getGetInstance().getString(SpArgument.INSTANCE.getAvatarUrl(), ""))));
        view.findViewById(R.id.viewFriendMain).setPadding(0, StatusBarUtil.getStatusBarHeight(getActivity()),0,0);
//        SDEventManager.register(this);
        mList = view.findViewById(R.id.rc_conversation_list);
        mRefreshLayout = view.findViewById(R.id.rc_refresh);
        mAdapter.setItemClickListener(this);
        LinearLayoutManager layoutManager = new FixedLinearLayoutManager(getActivity());
        mList.setLayoutManager(layoutManager);
        mList.addOnScrollListener(
                new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(
                            @NonNull RecyclerView recyclerView, int newState) {
                        Log.e(TAG, "onScrollStateChanged: " );
                        mNewState = newState;
                        if (mNewState == RecyclerView.SCROLL_STATE_IDLE
                                && delayRefresh
                                && mAdapter != null
                                && mConversationListViewModel != null) { // 滚动停止
                            delayRefresh = false;
                            mAdapter.setDataCollection(
                                    mConversationListViewModel
                                            .getConversationListLiveData()
                                            .getValue());
                        }
                    }
                });
        mNoticeContainerView = view.findViewById(R.id.rc_conversationlist_notice_container);
        mNoticeContentTv = view.findViewById(R.id.rc_conversationlist_notice_tv);
        mNoticeIconIv = view.findViewById(R.id.rc_conversationlist_notice_icon_iv);
        // 创建菜单：
        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
                if(position==0){
                    return;
                }
                int itemViewType = mAdapter.getItemViewType(position);
                if (itemViewType== -200){
                    return;
                }
                int width = getResources().getDimensionPixelSize(com.yoo.module_res.R.dimen.rc_margin_size_80);
                int height = getResources().getDimensionPixelSize(com.yoo.module_res.R.dimen.rc_margin_size_76);

                Typeface font = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    font = getContext().getResources().getFont(com.yoo.module_res.R.font.lexenddeca_regular);
                }
                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext())
                        .setBackgroundColor(Color.parseColor("#73FF3E4A"))
                        .setImage(com.yoo.module_res.R.drawable.ic_chat_ist_delete)
                        .setText("Delete")
                        .setTextColor(Color.WHITE)
                        .setTextTypeface(font)
                        .setTextSize(14)
                        .setWidth(width)
                        .setHeight(height);
                rightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。
            }

        };
        // 设置监听器。
        mList.setSwipeMenuCreator(mSwipeMenuCreator);
        OnItemMenuClickListener mItemMenuClickListener = new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int position) {
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu();
                CustomEventUtils.INSTANCE.logEvent(CustomEventTag.IM_Deletechat.name());

                // 菜单在Item中的Position：
                BaseUiConversation baseUiConversation = mAdapter.getData().get(position-1);
                IMCenter.getInstance()
                        .removeConversation(
                                baseUiConversation.mCore.getConversationType(),
                                baseUiConversation.mCore.getTargetId(),
                                new RongIMClient.ResultCallback<Boolean>() {
                                    @Override
                                    public void onSuccess(Boolean aBoolean) {
                                        new Handler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                mAdapter.setDataCollection(
                                                        mConversationListViewModel
                                                                .getConversationListLiveData()
                                                                .getValue());
                                            }
                                        },200);
                                    }

                                    @Override
                                    public void onError(RongIMClient.ErrorCode e) {
                                        Log.e(TAG, "onError: " );
                                    }
                                });

            }
        };

        mList.setSwipeItemMenuEnabled(0,false);
        // 菜单点击监听。
        mList.setOnItemMenuClickListener(mItemMenuClickListener);

        mList.setAdapter(mAdapter);

        initRefreshView();
        subscribeUi();
        addNotification();
    }

    /**
     * 无通知权限时展示
     */
    private void addNotification(){
        View inflate = View.inflate(getActivity(), R.layout.layout_chat_notication, null);
        addHeaderView(inflate);
        ImageView imgNotificationClose = inflate.findViewById(R.id.img_notification_close);
        ConstraintLayout notificationContainer = inflate.findViewById(R.id.notification_container);

        //通知权限栏是否展示
        notificationContainer.setVisibility((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !PermissionCheckUtil.checkPermissions(
                getActivity(),new String[]{Manifest.permission.POST_NOTIFICATIONS}
        ))?View.VISIBLE : View.GONE);

        //通知权限请求
        notificationContainer.setOnClickListener(v -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                XXPermissions.with(this).permission(Permission.POST_NOTIFICATIONS)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                                notificationContainer.setVisibility(View.GONE);
                            }

                            @Override
                            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                                OnPermissionCallback.super.onDenied(permissions, doNotAskAgain);
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.fromParts("package", getActivity().getApplicationInfo().packageName, null));
                                startActivityForResult(intent, Permission_Request);
                            }
                        });
            }
        });

        //关闭通知权限请求栏
        imgNotificationClose.setOnClickListener(v->{
            notificationContainer.setVisibility(View.GONE);
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mConversationListViewModel != null) {
            mConversationListViewModel.clearAllNotification();
        }
        ImmersionBar.with(this).statusBarDarkFont(false).init();
    }


    /** 初始化刷新模块 */
    protected void initRefreshView() {
        if (mRefreshLayout == null) {
            RLog.d(TAG, "initRefreshView null");
            return;
        }
        mRefreshLayout.setNestedScrollingEnabled(false);
        mRefreshLayout.setRefreshHeader(new RongRefreshHeader(getContext()));
        mRefreshLayout.setRefreshFooter(new RongRefreshHeader(getContext()));
        mRefreshLayout.setOnRefreshListener(
                new OnRefreshListener() {
                    @Override
                    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                        onConversationListRefresh(refreshLayout);
                    }
                });
        mRefreshLayout.setOnLoadMoreListener(
                new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        onConversationListLoadMore();
                    }
                });
    }

    /** 观察 view model 各数据以便进行页面刷新操作。 */
    protected void subscribeUi() {
        // 会话列表数据监听
        mConversationListViewModel =
                new ViewModelProvider(this).get(ConversationListViewModel.class);
        mConversationListViewModel.getConversationList(false, false, 0);
        mConversationListViewModel
                .getConversationListLiveData()
                .observe(
                        getViewLifecycleOwner(),
                        new Observer<List<BaseUiConversation>>() {
                            @Override
                            public void onChanged(List<BaseUiConversation> uiConversations) {
                                RLog.d(TAG, "conversation list onChanged.");
                                if (mNewState == RecyclerView.SCROLL_STATE_IDLE) {
                                    mAdapter.setDataCollection(uiConversations);
                                } else {
                                    delayRefresh = true;
                                }
                            }
                        });
        // 连接状态监听
        mConversationListViewModel
                .getNoticeContentLiveData()
                .observe(
                        getViewLifecycleOwner(),
                        new Observer<NoticeContent>() {
                            @Override
                            public void onChanged(NoticeContent noticeContent) {
                                // 当连接通知没有显示时，延迟进行显示，防止连接闪断造成画面闪跳。
                                if (mNoticeContainerView.getVisibility() == View.GONE) {
                                    mHandler.postDelayed(
                                            new Runnable() {
                                                @Override
                                                public void run() {
                                                    // 刷新时使用最新的通知内容
                                                    updateNoticeContent(
                                                            mConversationListViewModel
                                                                    .getNoticeContentLiveData()
                                                                    .getValue());
                                                }
                                            },
                                            NOTICE_SHOW_DELAY_MILLIS);
                                } else {
                                    updateNoticeContent(noticeContent);
                                }
                            }
                        });
        // 刷新事件监听
        mConversationListViewModel
                .getRefreshEventLiveData()
                .observe(
                        getViewLifecycleOwner(),
                        new Observer<Event.RefreshEvent>() {
                            @Override
                            public void onChanged(Event.RefreshEvent refreshEvent) {
                                if (refreshEvent.state.equals(RefreshState.LoadFinish)) {
                                    if (mRefreshLayout != null) {
                                        mRefreshLayout.finishLoadMore();
                                    } else {
                                        RLog.d(TAG, "onChanged finishLoadMore error");
                                    }
                                } else if (refreshEvent.state.equals(RefreshState.RefreshFinish)) {
                                    if (mRefreshLayout != null) {
                                        mRefreshLayout.finishRefresh();
                                    } else {
                                        RLog.d(TAG, "onChanged finishRefresh error");
                                    }
                                }
                            }
                        });
    }

    protected void onConversationListRefresh(RefreshLayout refreshLayout) {
        if (mConversationListViewModel != null) {
            mConversationListViewModel.getConversationList(false, true, 0);
        }
    }

    protected void onConversationListLoadMore() {
        if (mConversationListViewModel != null) {
            mConversationListViewModel.getConversationList(true, true, 0);
        }
    }

    /**
     * 更新连接状态通知栏
     *
     * @param content
     */
    protected void updateNoticeContent(NoticeContent content) {
        if (content == null) return;
        if (content.isShowNotice()) {
            mNoticeContainerView.setVisibility(View.VISIBLE);
            mNoticeContentTv.setText(content.getContent());
            if (content.getIconResId() != 0) {
                mNoticeIconIv.setImageResource(content.getIconResId());
            }
        } else {
            mNoticeContainerView.setVisibility(View.GONE);
        }
    }

    /**
     * 获取 adapter. 可复写此方法实现自定义 adapter.
     *
     * @return 会话列表 adapter
     */
    protected ConversationListAdapter onResolveAdapter() {
        mAdapter = new ConversationListAdapter();
        mAdapter.setEmptyView(R.layout.layout_chat_empty);
        return mAdapter;
    }

    /**
     * 会话列表点击事件回调
     *
     * @param view 点击 view
     * @param holder {@link ViewHolder}
     * @param position 点击位置
     */
    @Override
    public void onItemClick(View view, ViewHolder holder, int position) {
        if (position < 0 || position >= mAdapter.getData().size()) {
            return;
        }
        BaseUiConversation baseUiConversation = mAdapter.getItem(position);
        ConversationListBehaviorListener listBehaviorListener =
                RongConfigCenter.conversationListConfig().getListener();
        if (listBehaviorListener != null
                && listBehaviorListener.onConversationClick(
                        view.getContext(), view, baseUiConversation)) {
            RLog.d(TAG, "ConversationList item click event has been intercepted by App.");
            return;
        }
        Log.e(TAG, "onItemClick: " + baseUiConversation.mCore.getPortraitUrl());
        if (baseUiConversation != null && baseUiConversation.mCore != null) {
            if (baseUiConversation instanceof GatheredConversation) {
                RouteUtils.routeToSubConversationListActivity(
                        view.getContext(),
                        ((GatheredConversation) baseUiConversation).mGatheredType,
                        baseUiConversation.mCore.getConversationTitle());
            } else {
                RouteUtils.routeToConversationActivity(
                        view.getContext(), baseUiConversation.getConversationIdentifier());
            }
        } else {
            RLog.e(TAG, "invalid conversation.");
        }
    }

    /**
     * 会话列表长按事件回调
     *
     * @param view 点击 view
     * @param holder {@link ViewHolder}
     * @param position 点击位置
     * @return 事件是否被消费
     */
    @Override
    public boolean onItemLongClick(final View view, ViewHolder holder, int position) {
        if (position < 0 || position >= mAdapter.getData().size()) {
            return false;
        }
        final BaseUiConversation baseUiConversation = mAdapter.getItem(position);
        ConversationListBehaviorListener listBehaviorListener =
                RongConfigCenter.conversationListConfig().getListener();
        if (listBehaviorListener != null
                && listBehaviorListener.onConversationLongClick(
                        view.getContext(), view, baseUiConversation)) {
            RLog.d(TAG, "ConversationList item click event has been intercepted by App.");
            return true;
        }
        return true;
    }

    /** @param view 自定义列表 header view */
    public void addHeaderView(View view) {
        mAdapter.addHeaderView(view);
    }

    /** @param view 自定义列表 footer view */
    public void addFooterView(View view) {
        mAdapter.addFootView(view);
    }

    /** @param view 自定义列表 空数据 view */
    public void setEmptyView(View view) {
        mAdapter.setEmptyView(view);
    }

    /** @param emptyId 自定义列表 空数据的 LayoutId */
    public void setEmptyView(@LayoutRes int emptyId) {
        mAdapter.setEmptyView(emptyId);
    }
}
